package com.ciwong.epaper.modules.me.ui;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.me.bean.BindInfo;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.SchoolDetail;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.LogOutUtil;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.ViewUtil;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.NetworkUtils;
import com.ciwong.libs.widget.CWToast;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.ImageLoaderHelper;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.BottomMenuDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.ciwong.mobilelib.utils.fileprovider.FileProvider7;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.ciwong.epaper.modules.me.ui.SettingActivity.REQUEST_BIND_CODE;
import static com.ciwong.epaper.modules.me.ui.SettingActivity.SETING_BACK_RETURN;

/**
 * 个人信息
 *
 * @author sugy
 * @version ciwong v.1.0 2015/9/9 15:53
 * @since ciwong v.1.0
 */
public class MyInfoActivity extends BaseActivity implements View.OnClickListener {
    /**
     * 跳转码，拍照
     */
    public static final int REQUEST_CODE_CAMERA = 0x0000011;

    /**
     * 跳转码，相册
     */
    public static final int REQUEST_CODE_ALBUM = 0x0000012;

    /**
     * 跳转码，拍照裁剪图片
     */
    public static final int REQUEST_CODE_CROP_CAMERA = 0x0000013;

    /**
     * 跳转码，相册裁剪图片
     */
    public static final int REQUEST_CODE_CROP_ALBUM = 0x0000014;

    /**
     * 跳转码，班级
     */
    public static final int REQUEST_CODE_CLASS = 0x0000015;

    /**
     * 跳转码，切换学校
     */
    public static final int REQUEST_CODE_SCHOOL = 0x0000016;

    /**
     * 跳转码，修改性名
     */
    public static final int REQUEST_CODE_UPDATE_USERNAME = 0x0000017;

    private EApplication application;

    private ImageView ivAvatar;

    private Uri photoUri;

    private File tempFile;

    private View layoutAvatar, layoutName, layoutAccount, layoutClass,
            layoutSchool, layoutLianxiKefu;

    private TextView tvName, tvAccount, tvClass, tvSchool;

    private BottomMenuDialog bottomMenuDialog;

    private ViewGroup binded_phone_number;
    private ViewGroup settingModifyPassword;
    private TextView phone_number_tv;
    private CWDialog getSDcardPermissDialog;
    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;

    class BottomClickListener extends ViewOnClickListener {
        private int index;

        public BottomClickListener(int index) {
            this.index = index;
        }

        @Override
        public void avertRepeatOnClick(View v) {
            switch (index) {
                case 0:// 拍照
                    showgetCameraPermissDialog();
                    break;
                case 1:// 从相册选
                    showgetAlbumPermissDialog();
                    break;
                default:
                    break;
            }
            bottomMenuDialog.dismiss();
        }
    }

    private final int CODE_REQUEST_ALBUM_PERMISSION = 9900;
    private final int CODE_REQUEST_CAMERA_PERMISSION = 9901;
    private CWDialog getAlbumPermissDialog;

    /**
     * 获取Album权限提示框
     */
    private boolean showgetAlbumPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            useAlbum();
        } else {
            if (getAlbumPermissDialog == null) {
                getAlbumPermissDialog = new CWDialog(this);
                getAlbumPermissDialog.setTitle(R.string.get_permiss_title);
                getAlbumPermissDialog.setTitleTextColor(Color.BLACK);
                getAlbumPermissDialog.setMessage(getString(R.string.get_album_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getAlbumPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                        useAlbum();
                    }
                });
                getAlbumPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                    }
                });
            }
            getAlbumPermissDialog.show();
        }
        return true;
    }

    private CWDialog getCameraPermissDialog;

    /**
     * 获取Camera权限提示框
     */
    private boolean showgetCameraPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.CAMERA);
        if (isHavePermiss) {
            useCamera();
        } else {
            if (getCameraPermissDialog == null) {
                getCameraPermissDialog = new CWDialog(this);
                getCameraPermissDialog.setTitle(R.string.get_permiss_title);
                getCameraPermissDialog.setTitleTextColor(Color.BLACK);
                getCameraPermissDialog.setMessage(getString(R.string.get_camera_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getCameraPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                        useCamera();
                    }
                });
                getCameraPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                    }
                });
            }
            getCameraPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用相册，判断权限
     */
    private void useAlbum() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读取相册权限");
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_ALBUM_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                BaseJumpManager.jumpToSysAlbum(MyInfoActivity.this,
                                        REQUEST_CODE_ALBUM);
                            }
                        }
                    });
        } else {
            BaseJumpManager.jumpToSysAlbum(MyInfoActivity.this,
                    REQUEST_CODE_ALBUM);
        }
    }

    /**
     * 使用照相机，判断权限
     */
    private void useCamera() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList_camera = new ArrayList<String>();
            Map<String, String> noteMap_camera = new HashMap<>();
            noteMap_camera.put(Manifest.permission.CAMERA, "相机权限");
            permissionList_camera.add(Manifest.permission.CAMERA);
//            if (Build.VERSION.SDK_INT >= 30) {
//                permissionList_camera.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//                noteMap_camera.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读取相册权限");
//            }
            XXPermissionTool.checkPermissions(this, //
                    permissionList_camera, //
                    noteMap_camera, //
                    CODE_REQUEST_CAMERA_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                tempFile = ESystem.getPicturesCacheDir(MyInfoActivity.this, ESystem.getCacheFileName("meinfo", "jpg"));
                                BaseJumpManager.jumpToSysCamera(MyInfoActivity.this,
                                        tempFile, REQUEST_CODE_CAMERA);
                            }
                        }
                    });
        } else {
            tempFile = ESystem.getPicturesCacheDir(MyInfoActivity.this, ViewUtil.getPhotoFileName());
            BaseJumpManager.jumpToSysCamera(MyInfoActivity.this,
                    tempFile, REQUEST_CODE_CAMERA);
        }
    }

    private ALiYunManager.ALiYunListener listener = new ALiYunManager.ALiYunListener() {
        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {

        }

        @Override
        public void onSuccess(Object tag, String url) {
            FileUtils.delete(String.valueOf(tag));
            updateUserInfo(url);
            hideMiddleProgressBar();
        }

        @Override
        public void onFailure(Object tag, int errorCode) {//要根据tag的值来判断  这个监听者是全局的 所以没有tag 我把提示删了
            hideMiddleProgressBar();
            //showToastError(R.string.upload_avatar_fail);
        }
    };

    @Override
    protected int setView() {
        return R.layout.activity_my_info;
    }

    @Override
    protected void findViews() {
        layoutAvatar = findViewById(R.id.my_info_avatar_layout);
        layoutName = findViewById(R.id.my_info_name_layout);
        layoutAccount = findViewById(R.id.my_info_account_layout);
        layoutClass = findViewById(R.id.my_info_class_layout);
        layoutSchool = findViewById(R.id.my_info_school_layout);
        layoutLianxiKefu = findViewById(R.id.lianxi_kefu_layout);

        ivAvatar = findViewById(R.id.my_info_avatar);
        tvName = findViewById(R.id.my_info_name);
        tvAccount = findViewById(R.id.my_info_account);
        tvClass = findViewById(R.id.my_info_class);
        tvSchool = findViewById(R.id.my_info_school);

        settingModifyPassword = findViewById(
                R.id.setting_modify_password);
        binded_phone_number = findViewById(R.id.binded_phone_number);
        phone_number_tv = findViewById(R.id.phone_number_tv);
    }

    @Override
    protected void initEvent() {
        layoutAvatar.setOnClickListener(this);
        ivAvatar.setOnClickListener(this);
        // layoutName.setOnClickListener(this);
        layoutAccount.setOnClickListener(this);
//        layoutClass.setOnClickListener(this);
//        layoutSchool.setOnClickListener(this);
        layoutLianxiKefu.setOnClickListener(this);
        ALiYunManager.getInstance().registerListener(listener);
        settingModifyPassword.setOnClickListener(this);
        binded_phone_number.setOnClickListener(this);

        ((TextView) findViewById(R.id.lianxi_kefu_tx)).getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
    }

    @Override
    protected void init() {
        setTitleText(R.string.my_info);
        application = (EApplication) getApplication();
        showClassInfo(false);
        setBottomMenuDialog();
    }


    @Override
    protected void onResume() {
        super.onResume();
        phone_number_tv.setText(CWSys.getSharedString(EConstants.SHARE_PRE_CURR_LOGIN_USER_PHONE + SerializableManager.getInstance().getUserId(true)));
    }

    @Override
    protected void loadData() {
        getBindInfo((EApplication) getApplication(), EApplication.BRAND_ID + "", CWSys.getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "");
        UserInfoBase userInfo = getUserInfoBase();
        if (userInfo != null) {
            String avatar = userInfo.getAvatar();
            avatar = TextUtils.isEmpty(avatar) ? getString(R.string.default_avatar_file_path) + R.mipmap.head : avatar;
            try {
                if (!ImageLoader.getInstance().isInited()) {
                    ImageLoaderHelper.getInstance().init(getApplicationContext());
                }
                ImageLoader.getInstance().displayImage(avatar, ivAvatar, EConstants.getDefAvatarCircleBuilder());
            } catch (Exception e) {
                e.printStackTrace();
            }

            tvName.setText(userInfo.getRealName());
            tvAccount.setText(userInfo.getUserId() + "");


            if (application != null) {
                SchoolDetail schoolDetail = application.getSchoolDetail();

                if (schoolDetail != null && schoolDetail.getSchoolName() != null && !schoolDetail.getSchoolName().equals("")) {
                    tvSchool.setText(schoolDetail.getSchoolName());
                }
            }
        }
        getAndSerializeClassList();
    }


    private File cutImgFile;
    private File cutImgFileTemp;

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent data) {
        if (requestCode == REQUEST_BIND_CODE) {
            getBindInfo((EApplication) getApplication(), EApplication.BRAND_ID + "", CWSys.getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "");
        }
        if (resultCode == RESULT_OK) {
            Uri outPuturi;

            Intent intent = new Intent();
            switch (requestCode) {
                case REQUEST_CODE_CLASS:// 加班级成功后回调
                    showClassInfo(true);
                    break;
                case REQUEST_CODE_SCHOOL:// 修改学校成功后回调
                    SchoolDetail schoolDetail = application.getSchoolDetail();
                    if (schoolDetail != null && schoolDetail.getSchoolName() != null && !schoolDetail.getSchoolName().trim().equals("")) {
                        tvSchool.setText(schoolDetail == null ? ""
                                : schoolDetail.getSchoolName());
                    }
                    intent.putExtra(IntentFlag.INTENT_FLAG_TYPE,
                            IntentValue.ModifyUserInfoType.RESULT_MODIFY_SCHOOL);
                    setResult(RESULT_OK, intent);
                    break;
                case REQUEST_CODE_CAMERA:
                    photoUri = FileProvider7.getUriForFile(this, tempFile);
//                    if (Build.VERSION.SDK_INT >= 30) {
                    cutImgFile = FileUtil.uriToPicturesFileApiQ(photoUri, MyInfoActivity.this);
//                    } else {
//                        cutImgFile = new File(ESystem.getUploadImgPath(), ESystem.getCacheFileName("meinfo", "jpg"));
//                    }
//                    outPuturi = Uri.fromFile(cutImgFile);
//                    CWLog.i("byou", "outPuturi=" + outPuturi);
//                    BaseJumpManager.jumpToSysCropPhoto(this, photoUri, outPuturi,
//                            REQUEST_CODE_CROP_CAMERA, true, 200, 200, true);
                    showGetPermissDialog();
                    break;
                case REQUEST_CODE_ALBUM:
                    if (data != null) {
                        photoUri = data.getData();
                        if (photoUri != null) {
//                            if (Build.VERSION.SDK_INT >= 30) {
                            cutImgFile = FileUtil.uriToPicturesFileApiQ(photoUri, MyInfoActivity.this);
//                            } else {
//                                cutImgFile = new File(ESystem.getUploadImgPath(), ESystem.getCacheFileName("meinfo", "jpg"));
//                            }
                            showGetPermissDialog();
                        }
                    }
                    break;
                case REQUEST_CODE_CROP_ALBUM:
                case REQUEST_CODE_CROP_CAMERA:
                    if (null != cutImgFileTemp) {
                        CWLog.i("byou", "cutImgFile.getPath()=" + cutImgFile.getPath());
                        if (Build.VERSION.SDK_INT >= 30) {
                            cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.getCropFile(getBaseContext(), com.ciwong.mobilelib.utils.FileUtil.uri);
                        }
                        uploadAvatar(cutImgFileTemp.getPath());
                    }
                    break;
                // 更新姓名
                case REQUEST_CODE_UPDATE_USERNAME:
                    if (data != null && data.getBooleanExtra(
                            UpdateUserNameActivity.IS_NEED_UPDATE_USERNAME,
                            false)) {
                        loadData();
                        intent.putExtra(IntentFlag.INTENT_FLAG_TYPE,
                                IntentValue.ModifyUserInfoType.RESULT_MODIFY_NAME);
                        setResult(RESULT_OK, intent);
                    }
                    break;
                case CODE_REQUEST_ALBUM_PERMISSION:
                    if (XXPermissionTool.isHasPermission(MyInfoActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        BaseJumpManager.jumpToSysAlbum(MyInfoActivity.this,
                                REQUEST_CODE_ALBUM);
                    }
                    break;
                case CODE_REQUEST_CAMERA_PERMISSION:
                    if (XXPermissionTool.isHasPermission(MyInfoActivity.this, Manifest.permission.CAMERA)) {
                        tempFile = ESystem.getPicturesCacheDir(MyInfoActivity.this, ViewUtil.getPhotoFileName());
                        BaseJumpManager.jumpToSysCamera(MyInfoActivity.this,
                                tempFile, REQUEST_CODE_CAMERA);
                    }
                    break;
                default:
                    break;
            }
        }
    }

    /**
     * 获取SDcard权限提示框
     */
    private boolean showGetPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(this);
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_photo_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, getString(R.string.read_and_write_local_storage_permissions));
            XXPermissionTool.checkPermissions(this, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                Uri outPuturi = Uri.fromFile(cutImgFile);
                                Uri imgUri = FileProvider7.getUriForFile(MyInfoActivity.this, cutImgFile);

                                if (Build.VERSION.SDK_INT >= 30) {
                                    cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.createImageFile(getBaseContext(), true);
                                    //设置裁剪的图片地址Uri
                                    outPuturi = com.ciwong.mobilelib.utils.FileUtil.uri;
                                } else {
                                    cutImgFileTemp = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".png");
                                }
                                BaseJumpManager.jumpToSysCropPhoto(MyInfoActivity.this, imgUri, outPuturi, cutImgFileTemp,
                                        REQUEST_CODE_CROP_CAMERA, true, 200, 200);
                            } else {
//                                showConfirmCommitDialog(getActivity(), "未获取到读写本地存储权限。");
                            }
                        }
                    });
        } else {
            Uri outPuturi = Uri.fromFile(cutImgFile);
            Uri imgUri = FileProvider7.getUriForFile(MyInfoActivity.this, cutImgFile);
            if (Build.VERSION.SDK_INT >= 30) {
                cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.createImageFile(getBaseContext(), true);
                outPuturi = com.ciwong.mobilelib.utils.FileUtil.uri;
                //设置裁剪的图片地址Uri
            } else {

                cutImgFileTemp = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".png");
            }
            BaseJumpManager.jumpToSysCropPhoto(MyInfoActivity.this, imgUri, outPuturi, cutImgFileTemp,
                    REQUEST_CODE_CROP_CAMERA, true, 200, 200);
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ALiYunManager.getInstance().unRegisterListener(listener);
    }

    // 使用系统当前日期加以调整作为照片的名称
    public static String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".jpg";
    }

    private void setBottomMenuDialog() {
        bottomMenuDialog = new BottomMenuDialog(this);
        bottomMenuDialog
                .setBtnTextColor(getResources().getColor(R.color.color_light_green));
        bottomMenuDialog
                .setLastBtnTextColor(getResources().getColor(R.color.gray));

        ArrayList<String> str = new ArrayList<>();

        str.add(getResources().getString(R.string.avatar_camera));
        str.add(getResources().getString(R.string.avatar_photo));
        str.add(getResources().getString(android.R.string.cancel));
        bottomMenuDialog.setMenuTextList(str);

        ArrayList<View.OnClickListener> listeners = new ArrayList<>();

        listeners.add(new BottomClickListener(0));
        listeners.add(new BottomClickListener(1));
        listeners.add(new BottomClickListener(2));

        bottomMenuDialog.setMenuOnClickListeners(listeners);
    }

    /**
     * 获取并缓存班级列表
     */
    private void getAndSerializeClassList() {
        try {
            showMiddleProgressBar(getTitleText());
            MeDao.getInstance().getClassList(EApplication.BRAND_ID,
                    new BaseExtCallBack(MyInfoActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
                        @Override
                        public void success(Object data) {
                            hideMiddleProgressBar();
                            List<Clazz> clazzs = (List<Clazz>) data;
                            Clazz clazz = application.getClazz();
                            if (clazzs == null || clazzs.isEmpty()) {
                                clazz = null;
                            } else {
                                int indexOf = clazzs.indexOf(clazz);
                                if (indexOf < 0) {
                                    indexOf = 0;
                                }
                                clazz = clazzs.get(indexOf);
                            }
                            SerializableManager.getInstance().serialize(
                                    SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT,
                                    clazz);
                            // 缓存班级列表
                            SerializableManager.getInstance().serialize(
                                    SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST,
                                    (Serializable) clazzs);
                            application.setClazzs(clazzs);
                            showClassInfo(true);
                        }

                        @Override
                        public void failed(int errorCode, Object data) {
                            super.failed(errorCode, data);
                            hideMiddleProgressBar();
                            CWLog.d("MyInfo", "拉取班级列表失败:" + errorCode);
                        }

                        @Override
                        public void failed(Object data) {
                            hideMiddleProgressBar();
                            CWLog.d("MyInfo", "拉取班级列表失败:" + data);
                        }
                    });


        } catch (NullPointerException e) {

        }
    }

    /**
     * 显示班级信息
     *
     * @param result 是否需要返回结果
     */
    private void showClassInfo(boolean result) {
        // 显示班级信息
        Clazz clazz = application.getClazz();
        tvClass.setText(clazz == null ? getString(R.string.no_add) : clazz.getClassName());

        if (clazz != null) {
            if (TextUtils.isEmpty(tvSchool.getText().toString()) && clazz.getSchoolName() != null && !clazz.getSchoolName().equals("")) {
                tvSchool.setText(clazz.getSchoolName());
            }
        }

        if (result) {
            Intent intent = new Intent();
            intent.putExtra(IntentFlag.INTENT_FLAG_TYPE,
                    IntentValue.ModifyUserInfoType.RESULT_MODIFY_CLASS);
            setResult(RESULT_OK, intent);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.my_info_avatar_layout) {
            bottomMenuDialog.show();
        } else if (id == R.id.my_info_avatar) {
            if (!TextUtils.isEmpty(getUserInfoBase().getAvatar())) {
                ArrayList<String> urlList = new ArrayList<String>();
                urlList.add(getUserInfoBase().getAvatar());
                BaseJumpManager.jumpToScanImage(this, R.string.go_back, urlList, 0);
            }
        } else if (id == R.id.my_info_name_layout) {
            MeJumpManager.jumpToUpdateUserNameActivity(this, R.string.my_info,
                    REQUEST_CODE_UPDATE_USERNAME);
        } else if (id == R.id.my_info_class_layout) {

            if (NetworkUtils.isOnline()) {
                if (null == application.getClazz()) {
                    MeJumpManager.jumpToJoinClassActivity(R.string.go_back,
                            this, IntentValue.JumpToJoinClassType.TYPE_JOIN_CLASS, REQUEST_CODE_CLASS);
//                 MeJumpManager.jumpToJoinClassActivity(R.string.go_back, this,
//                 IntentValue.JumpToJoinClassType.FROM_MY_INFO, 0);
                } else {
                    MeJumpManager.jumpToClassList(this, R.string.go_back, IntentValue.JumpToJoinClassType.TYPE_CHECK_CLASS_LIST,
                            REQUEST_CODE_CLASS, null, null);
                }
            } else {

                CWToast.centerSquareError(MyInfoActivity.this, R.string.connect_disable).show();

            }
        } else if (id == R.id.my_info_school_layout) {
            MeJumpManager.jumpToChooseSchool(R.string.go_back, this,
                    IntentValue.ChooseSchoolType.CHOOSE_SCHOOL_TYPE_MANUAL,
                    REQUEST_CODE_SCHOOL);
        } else if (id == R.id.binded_phone_number) {
            String phoneNumber = phone_number_tv.getText().toString();
            if (phoneNumber != null) {
                MeJumpManager.jumpToModifyPhone(MyInfoActivity.this, R.string.go_back, phoneNumber);
            }
        } else if (id == R.id.setting_modify_password) {
            MeJumpManager.jumpToModifyPassword(R.string.go_back,
                    MyInfoActivity.this);
        } else if (id == R.id.lianxi_kefu_layout) {
            MeJumpManager.jumpToKeFu(MyInfoActivity.this, R.string.go_back);
        }
    }

    /**
     * 裁剪后的图片路径
     *
     * @param data
     * @return
     */
    public static String getCropPath(Intent data) {
        Bitmap bitmap = data.getParcelableExtra("data");
        if (bitmap != null) {
            FileOutputStream fos = null;
            File file = new File(ESystem.getUploadImgPath(),
                    getPhotoFileName());
            try {
                fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();
                }
            }
            return file.getPath();
        }
        return "";
    }

    /**
     * 上传头像
     */
    private void uploadAvatar(final String localPath) {
        File file = new File(localPath);
        if (file.exists()) {
            showMiddleProgressBar(getTitleText());
            ALiYunManager.getInstance().addFile(localPath, ALiYunManager.getInstance().getKey(localPath), localPath);
        } else {
            showToastError("文件不存在");
        }
    }

    /**
     * 修改用户信息
     *
     * @param avatar 用户头像
     */
    private void updateUserInfo(final String avatar) {
        MeDao.getInstance().updateUserInfo(avatar, new BaseExtCallBack(MyInfoActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {

            @Override
            public void success(Object data) {
                if (avatar != null) {
                    //获取积分（首次修改头像成功后）
                    MeDao.getInstance().getUserPoint();
                    // 修改头像成功
                    showToastSuccess(R.string.modify_avatar_success);
                    ToastUtil.INSTANCE.toastCenterSuccess(R.string.modify_avatar_success);
                    if (!ImageLoader.getInstance().isInited()) {
                        ImageLoaderHelper.getInstance().init(getApplicationContext());
                    }
                    ImageLoader.getInstance().displayImage(avatar, ivAvatar,
                            EConstants.getDefAvatarCircleBuilder());
                    getUserInfoBase().setAvatar(avatar);
                    Intent intent = new Intent();
                    intent.putExtra(IntentFlag.INTENT_FLAG_TYPE,
                            IntentValue.ModifyUserInfoType.RESULT_MODIFY_AVATAR);
                    setResult(RESULT_OK, intent);
                }

                SerializableManager.getInstance().serialize(
                        BaseConstants.SHARE_KEY_USER_INFO_BASE,
                        getUserInfoBase(), false);
                hideMiddleProgressBar();
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideMiddleProgressBar();
                if (errorCode == 90002) {
                    showToastError(errorCode, data);
                } else {
                    showToastError(R.string.modify_avatar_fail);
                }
            }

            @Override
            public void failed(Object data) {
                hideMiddleProgressBar();
                //showToastError(R.string.modify_avatar_fail);
            }
        });
    }


    public void getBindInfo(EApplication application, String business_id, String userId) {
        try {
            MeDao.getInstance().getBindInfo(application, business_id, userId, new BaseExtCallBack(MyInfoActivity.this, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
                @Override
                public void failed(int errorCode, Object data) {
                    super.failed(errorCode, data);
                    //未绑定手机号错误码
                    if (EConstants.UNBIND_PHONE_CODE_ERROR == errorCode) {
                        refData();
                    }
                }

                @Override
                public void failed(Object data) {
                    //网络请求失败情况下
                    DialogUtil.showFailedToastByErrorType(MyInfoActivity.this, data);
                }

                @Override
                public void success(Object data) {
                    BindInfo bindInfo = (BindInfo) data;
                    if (bindInfo != null) {
                        CWSys.setSharedString(EConstants.SHARE_PRE_CURR_LOGIN_USER_PHONE + SerializableManager.getInstance().getUserId(true), bindInfo.getMobile());
                    }
                }
            });
        } catch (NullPointerException e) {

        }

    }

    private void refData() {
        CWSys.setSharedString(EConstants.SHARE_PRE_CURR_LOGIN_USER_PHONE + SerializableManager.getInstance().getUserId(true), "");
        try {
            if (!isFinishing()) {
                CWDialog dialog = new CWDialog(this);
                String userId = SerializableManager.getInstance().getUserId(true);
                if (null != userId && userId.contains(",")) {
                    //去除对于得,

                    userId = userId.replace(",", "");
                }
                dialog.setMessage("你的帐号(" + userId + ")已被管理员解除手机号的绑定，为了保证正常使用，请重新绑定手机号。");
                dialog.setNegativeButton("退出登录", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        LogOutUtil.logOut(MyInfoActivity.this);
                        //销毁窗体
                        dialog.dismiss();
                    }
                });
                dialog.setPositiveButton("重新绑定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        //跳转绑定手机号页面  4代表来自换绑页面
                        MeJumpManager.jumpToBindPhoneActivity(R.string.go_back, MyInfoActivity.this, "", "4", SETING_BACK_RETURN, REQUEST_BIND_CODE);
                        //销毁窗体
                        dialog.dismiss();
                    }
                });
                dialog.show();

            }
        } catch (WindowManager.BadTokenException e) {

        }


    }
}
